package com.qf.service;
import com.qf.entity.SysUser;
import com.qf.mapper.SysUserMapper;
import com.qf.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;

@Service

public class SysUserServiceImpl implements SysUserService{
    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtUtils jwtUtils;
    @Override
    public void register(SysUser sysUser) {
        System.out.println("注册用户:"+sysUser);

        // 密码加密
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder( );
        String encode = passwordEncoder.encode(sysUser.getPassword());
        System.out.println("加密后密码 = " + encode);
        sysUser.setPassword(encode);

        // 调用Mapper层的注册方法
        sysUserMapper.save(sysUser);
    }
    @Override
    public String login(SysUser sysUser) {
        try {
        Authentication authenticate = authenticationManager.
                authenticate(new UsernamePasswordAuthenticationToken(sysUser.getUsername(), sysUser.getPassword()));

        HashMap<String, Object> map = new HashMap<>();
        map.put("username", authenticate.getName());
        map.put("perms", authenticate.getAuthorities());
        return jwtUtils.createToken(map);
    } catch (Exception e) {
            System.err.println("登录失败: " + e.getMessage());
            e.printStackTrace();
        throw new RuntimeException("用户名或密码错误");
    }
}}
